package com.hjq.interceptor;

import com.hjq.utils.CurrentHolder;
import com.hjq.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 令牌校验拦截器
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // log.info("访问路径，{}",request.getRequestURL());
        // // 访问登录页
        // if(request.getRequestURL().toString().contains("login")){
        //     return true;
        // }

        // 访问非登录页
        String token = request.getHeader("Token");
        // token不存在
        if(token==null || token.isEmpty()){
            log.info("token 不存在");
            response.setStatus(401);
            return false;
        }else{
            // token非法
            try {
                Claims claims = JwtUtils.parseJWT(token);
                Object id = claims.get("id");
                log.info("Token解析到的id:{}",id);
                // 存储到线程本地变量
                CurrentHolder.setCurrentId((Integer) id);
            } catch (Exception e) {
                log.info("token 不合法");
                response.setStatus(401);
                return false;
            }
        }
        // token合法
        log.info("token 合法");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求执行完毕后，清除线程本地变量中的数据，释放资源
        CurrentHolder.remove();
    }
}
